//
//  ModuleViewController.m
//  jungoo
//
//  Created by Sinbad Fly on 8/20/12.
//  Copyright (c) 2012 ABOM. All rights reserved.
//

#import "ModuleViewController.h"
#import "Extensions.h"

#define kCATag 1

@implementation ModuleViewController

@synthesize moduleMode = _moduleMode, autocompleteView = _autocompleteView, modules = _modules;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];    
}

#pragma mark - Private API

- (UITableViewCell*)moduleCellStyle1
{
    NSArray * views = [[NSBundle mainBundle] loadNibNamed:@"ModuleCell" owner:nil options:nil];
    
    return [views objectAtIndex:0];
}

- (UITableViewCell*)moduleCellStyle2
{
    NSArray * views = [[NSBundle mainBundle] loadNibNamed:@"ModuleCell" owner:nil options:nil];
    
    return [views objectAtIndex:1];
}

- (void)applyAppearance
{        
    [self.navigationItem setHidesBackButton:YES];
    
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"done-button" 
                                 target:self 
                                 action:@selector(done:)];
    
    [self setTitle:@"Modules"];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
     _autocompleteView = [[AutocompleteView alloc] initWithFrame:CGRectMake(0, 58, 320, 368)];
    
    if (self.modules == nil) {
        dataSource = [[NSMutableArray alloc] initWithObjects:@"",@"",@"",@"",nil];
    }
    else {
        dataSource = [[NSMutableArray arrayWithArray:self.modules] retain];
    }
}


- (void)onSetAutocompleteDataSource:(NSArray*)aDataSource
{
    _autocompleteView.dataSource = aDataSource;
    _autocompleteView.keyName = @"code";
    _autocompleteView.delegate = (id)self;
}

- (void)asyncLoadModules
{
    if ([JGoUtility sharedModules] == nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
        
        dispatch_async(queue, ^{
            
            NSError *error = nil;
            NSArray *getmodules = [JGoAPI getModules:&error];
            
            if (error) {
                LOG(@"%@",[error localizedDescription]);
            }
            else {
                
                [self performSelectorOnMainThread:@selector(onSetAutocompleteDataSource:) 
                                       withObject:getmodules 
                                    waitUntilDone:YES];
                [JGoUtility setModules:getmodules];
            }
        });  
    }
    else {
        [self onSetAutocompleteDataSource:[JGoUtility sharedModules]];
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg.png"]]];
    [self applyAppearance];
    [self asyncLoadModules];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [dataSource release];
    [_autocompleteView release];    
    [self setModules:nil];
    [super dealloc];
}

#pragma mark - Action

- (void)done:(id)sender
{   
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    NSMutableArray * modules = [[NSMutableArray new] autorelease];
    
    for (NSString *aModule in dataSource) {
        
        if ([aModule length]) {
            [modules addObject:aModule];
        }
    }
    
    if ([modules count]) {
        [[JGoUtility sharedCreateAccount] setValue:modules forKey:@"modules"];
    }
    
    [self.navigationController popViewControllerAnimated:YES];     
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addModule:(id)sender
{
    [dataSource addObject:@""];
    [self.tableView reloadData];
    [self performSelector:@selector(delayScrollTableView) withObject:nil afterDelay:0.1];
}

#pragma mark - TableView Delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataSource count] + 1;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.row < [dataSource count]) {
        cell = [self moduleCellStyle1];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell fieldTextWithTag:kCATag].delegate = (id)self;
        [cell fieldTextWithTag:kCATag].text = [dataSource objectAtIndex:indexPath.row];
    }
    else {
        cell = [self moduleCellStyle2];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [[cell buttonWithTag:kCATag] addTarget:self action:@selector(addModule:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}

#pragma mark - Delay Method

- (void)delayScrollTableView
{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[dataSource count] inSection:0]
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
}

#pragma mark - TextField Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 358, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:NO];
    
    [self.view addSubview:_autocompleteView];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    if ([indexPath isKindOfClass:[NSIndexPath class]]) {
        [dataSource replaceObjectAtIndex:indexPath.row withObject:textField.text];
    }
    
    [_autocompleteView searchAutocompleteEntriesWithSubstring:@""];
    [_autocompleteView removeFromSuperview];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    if ([indexPath isKindOfClass:[NSIndexPath class]]) {
        [dataSource replaceObjectAtIndex:indexPath.row withObject:textField.text];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *substring = [NSString stringWithString:textField.text];    
    substring = [substring stringByReplacingCharactersInRange:range withString:string];
    [_autocompleteView searchAutocompleteEntriesWithSubstring:substring];
    [_autocompleteView setUserInfo:textField];
    
    return YES;
}

#pragma mark - AutocompleteView Delegate

- (void)autocompleteView:(AutocompleteView *)autocompleteView didSeletedWithString:(NSString *)aString
{
    UITextField *textField = (id)autocompleteView.userInfo;
    
    if ([textField isKindOfClass:[UITextField class]]) {
        textField.text = aString;
    }
}

@end
